import 'package:cbec_app/components/base/base_function.dart';
import 'package:cbec_app/components/common/not_found.dart';
import 'package:flutter/material.dart';
import 'package:cbec_app/components/base/base_chekbox.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

//优惠券弹窗
class CouponPopup extends StatefulWidget {
  ///节省金额
  final double amount;

  ///使用优惠券数量
  final int couponNum;

  ///优惠券列表
  final List couponList;

  ///已经选择的优惠券列表
  final List selectedCouponIds;

  ///原价
  final double originPrice;

  ///回调
  final CallBackUseCoupon? callback;

  ///类型 1 优惠券 2 红包
  final int? type;

  const CouponPopup({
    super.key,
    required this.couponList,
    this.callback,
    required this.originPrice,
    this.type = 1,
    required this.amount,
    required this.couponNum,
    required this.selectedCouponIds,
  });

  @override
  State<CouponPopup> createState() => _CouponPopupState();
}

///被选中的优惠券ID
List<String> couponIds = [];

///选中的优惠券数量
int chooseNum = 0;

///节省了多少钱
double amount = 0.00;

///已经有叠加的券了
bool hasDj = false;

class _CouponPopupState extends State<CouponPopup> {
  @override
  void initState() {
    super.initState();
    amount = widget.amount;
    chooseNum = widget.couponNum;
    print(chooseNum);

    if (chooseNum == 0) {
      couponIds = [];
      hasDj = false;
    }

    for (var coupon in widget.couponList) {
      coupon['selected'] = widget.selectedCouponIds.any((couponId) {
        return coupon['couponUserId'].toString() == couponId.toString();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    String typeTxt = widget.type == 1 ? '请选择优惠券' : '红包';
    return Container(
        width: double.infinity,
        height: MediaQuery.of(context).size.height * 0.7,
        decoration: BoxDecoration(
          color: Tools.fromHex("#F3F5F7"),
          borderRadius: const BorderRadius.only(topLeft: Radius.circular(8), topRight: Radius.circular(8)),
        ),
        child: Stack(
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(
                  // color: Colors.red,
                  height: 66.w,
                  width: double.infinity,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Padding(
                        padding: const EdgeInsets.only(left: 20),
                        child: GestureDetector(
                            child: Text(
                              '取消',
                              style: TextStyle(
                                color: Tools.fromHex('#333333'),
                              ),
                            ),
                            onTap: () {
                              Get.back();
                            }),
                      ),
                      Expanded(
                          child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Text(typeTxt, style: setTextStyle(15, FontWeight.w700, Tools.fromHex("#000000"))),
                          Visibility(
                            visible: false,
                            child: Text(
                              "可用$typeTxt${widget.couponList.length}",
                              style: setTextStyle(
                                15,
                                FontWeight.w700,
                                Tools.fromHex("#FFFFFF"),
                              ),
                            ),
                          ),
                        ],
                      )),
                      GestureDetector(
                          child: Text(
                            '确定',
                            style: TextStyle(color: Tools.fromHex('#F83F2D')),
                          ),
                          onTap: () {
                            submit();
                          }),
                      SizedBox(width: 18.w)
                    ],
                  ),
                ),
                Visibility(
                  visible: false,
                  child: Container(
                    padding: EdgeInsets.only(left: 10.w, top: 10.w),
                    child: Row(
                      children: [Text("已选中推荐优惠，使用$typeTxt$chooseNum张，共抵扣", style: setTextStyle(12, FontWeight.w300, Tools.fromHex("#333333"))), Text("￥$amount", style: setTextStyle(12, FontWeight.w300, Tools.fromHex("#F83F2D")))],
                    ),
                  ),
                ),
                Container(
                  height: MediaQuery.of(context).size.height * 0.7 - 66.w,
                  color: Tools.fromHex('#f7f7f7'),
                  padding: EdgeInsets.all(10.w),
                  child: SingleChildScrollView(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: widget.couponList.isNotEmpty
                          ? List.generate(widget.couponList.length, (index) {
                              final Map item = widget.couponList[index];
                              // print('item ====== $item');
                              if (widget.type == 2) {
                                item['drop'] = item['price'];
                                item['name'] = item['redPacketName'];
                                item['goodsType'] = '全部商品可用';
                                item['validityStartTime'] = item['startTime'];
                                item['validityEndTime'] = item['endTime'];
                                item['discountDetails'] = "暂无使用说明";
                                item['actSuper'] = 1; //可以叠加使用
                                item['typeValue'] = 1; //红包全是满减
                                item['dropValue'] = item['price'];
                                item['couponUserId'] = item['redPacketId'];
                              }
                              return Container(
                                color: Colors.white,
                                child: Column(
                                  children: [
                                    Padding(
                                      padding: const EdgeInsets.all(8.0),
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          Row(
                                            children: [
                                              Text(
                                                '[${item['type']}]',
                                                style: TextStyle(color: Tools.fromHex('#000000'), fontSize: 14, fontWeight: FontWeight.bold),
                                              ),
                                              Text(
                                                item['name'],
                                                style: TextStyle(color: Tools.fromHex('#333333'), fontSize: 13),
                                              ),
                                            ],
                                          ),
                                          Column(
                                            children: [
                                              Row(
                                                children: [
                                                  Text(
                                                    '¥',
                                                    style: TextStyle(color: Tools.fromHex('#ed6072'), fontSize: 13),
                                                  ),
                                                  Text(
                                                    item['dropValue'].toString(),
                                                    style: TextStyle(
                                                      color: Tools.fromHex('#ed6072'),
                                                      fontSize: 18,
                                                      fontWeight: FontWeight.bold,
                                                    ),
                                                  ),
                                                ],
                                              ),
                                              Text(
                                                item['content'],
                                                style: TextStyle(color: Tools.fromHex('#333333'), fontSize: 13),
                                              ),
                                            ],
                                          )
                                        ],
                                      ),
                                    ),
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        // 左半圆
                                        CustomPaint(
                                          size: const Size(10, 10),
                                          painter: HalfCirclePainter(leftSide: true),
                                        ),
                                        Expanded(
                                          child: Container(
                                            height: 1,
                                            decoration: BoxDecoration(
                                              border: Border.all(
                                                color: Colors.transparent,
                                                width: 1.0,
                                              ),
                                            ),
                                            child: CustomPaint(
                                              painter: DottedLinePainter(),
                                            ),
                                          ),
                                        ),
                                        // 右半圆
                                        CustomPaint(
                                          size: const Size(10, 10),
                                          painter: HalfCirclePainter(leftSide: false),
                                        ),
                                      ],
                                    ),
                                    Padding(
                                      padding: const EdgeInsets.all(8.0),
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text(
                                            item['goodsType'],
                                            style: TextStyle(color: Tools.fromHex('#999999'), fontSize: 13),
                                          ),
                                          BaseCheckBox(
                                            value: widget.couponList[index]['selected'] ?? false,
                                            onChange: (selected) {
                                              change(item, index, selected);
                                            },
                                          ),
                                        ],
                                      ),
                                    )
                                  ],
                                ),
                              );
                            })
                          : [NotFound(txt: "暂无可用$typeTxt")],
                    ),
                  ),
                ),
              ],
            ),
          ],
        ));
  }

  //选择优惠券
  void change(Map item, int index, bool value) {
    setState(() {
      widget.couponList[index]['selected'] = value;
      if (value == true) {
        if (hasDj == true) {
          Tools.showToast("使用的券中包含了无法叠加的券,请先取消后再选择");
          widget.couponList[index]['selected'] = false;
          return;
        }

        //检测是否能叠加使用
        if (item['actSuper'] == 0) {
          hasDj = true; //记录已叠加

          //不能叠加
          if (couponIds.isNotEmpty) {
            Tools.showToast("该券不能叠加使用");
            widget.couponList[index]['selected'] = false;
            hasDj = false;
            return;
          }
        }

        //选中
        switch (item['typeValue']) {
          //满减
          case 1:
            amount += item['dropValue'];
            //不需要管
            break;
          //满折
          case 2:
            amount += double.parse((widget.originPrice * item['dropValue'] / 10).toStringAsFixed(2));
            // print("原价：${widget.originPrice}");
            // print("打折：${item['dropValue'] / 10}");
            // print("打折后：${double.parse((widget.originPrice * item['dropValue'] / 10).toStringAsFixed(2))}");
            break;
          //随机金额
          case 3:
            amount += item['dropValue'] ?? 0;
            break;
          //全减
          case 4:
            amount += widget.originPrice;
            break;
          default:
        }

        couponIds.add(item['couponUserId']);
        chooseNum += 1;
      } else {
        //取消选中
        if (item['actSuper'] == 0) {
          hasDj = false; //解锁
        }

        couponIds.remove(item['couponUserId']);
        chooseNum -= 1;

        //选中
        switch (item['typeValue']) {
          //满减
          case 1:
            amount -= item['dropValue'];
            //不需要管
            break;
          //满折
          case 2:
            amount -= double.parse((widget.originPrice * item['dropValue'] / 10).toStringAsFixed(2));
            break;
          //随机金额
          case 3:
            amount -= item['dropValue'] ?? 0;
            break;
          //全减
          case 4:
            amount -= widget.originPrice;
            break;
          default:
        }
      }
    });
  }

  //提交选择
  void submit() {
    widget.callback!(couponIds, amount.toString());

    Get.back();
  }
}

///唤起优惠券弹窗
void showCouponPopup(
  List selectedCouponIds,
  List couponList,
  double price,
  CallBackUseCoupon callback,
  double amount,
  int couponNum, {
  int? type = 1,
}) {
  showCupertinoModalPopup(
      context: Get.context!,
      builder: (context) {
        return CouponPopup(
          couponList: couponList,
          originPrice: price,
          callback: callback,
          type: type,
          couponNum: couponNum,
          amount: amount,
          selectedCouponIds: selectedCouponIds,
        );
      });
}

// 绘制半圆
class HalfCirclePainter extends CustomPainter {
  final bool leftSide; // 是否是左侧的半圆

  HalfCirclePainter({required this.leftSide});

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = Tools.fromHex('#f3f3f3') // 半圆的颜色
      ..style = PaintingStyle.fill;

    double radius = size.height / 2; // 半圆的半径，使用高度的一半作为半径

    if (leftSide) {
      // 绘制左半圆（右半圆方向的竖直半圆）
      canvas.drawArc(
        Rect.fromCircle(center: Offset(0, size.height / 2), radius: radius),
        -3.14 / 2, // 起始角度，绘制右半圆
        3.14, // 扫描角度，绘制半圆（π radians）
        true, // 是否闭合路径
        paint,
      );
    } else {
      // 绘制右半圆（左半圆方向的竖直半圆）
      canvas.drawArc(
        Rect.fromCircle(center: Offset(size.width, size.height / 2), radius: radius),
        3.14 / 2, // 起始角度，绘制左半圆
        3.14, // 扫描角度，绘制半圆（π radians）
        true, // 是否闭合路径
        paint,
      );
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}

// 绘制虚线
class DottedLinePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = Tools.fromHex('#ededed')
      ..strokeWidth = 1
      ..style = PaintingStyle.stroke;

    // 创建一个路径来绘制虚线
    Path path = Path();
    double dashWidth = 5.0;
    double dashSpace = 3.0;
    double startX = 0.0;

    while (startX < size.width) {
      path.moveTo(startX, 0); // 从 (startX, 0) 开始绘制
      path.lineTo(startX + dashWidth, 0); // 绘制一段线
      startX += dashWidth + dashSpace; // 移动到下一个虚线段
    }

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}
